import pygame
from plane_tools import *

class PlaneGame(object):

    # 游戏的初始化
    def __init__(self):
        pygame.init()

        # 设置屏幕
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        # 设置时钟
        self.clock = pygame.time.Clock()
        # 创建精灵组
        self.__create_sprite()

        pygame.time.set_timer(ENEMY_EVENT, 1000//enemy_come_speed)
        pygame.time.set_timer(FIRE_BULLET_EVENT, 1000//bullet_fire_speed)
        pygame.time.set_timer(WAKE_FLAME_EVENT, 100)

    def __create_sprite(self):
        bj = BackGround()
        bj2 = BackGround(True)
        self.bj_group = pygame.sprite.Group(bj, bj2)

        enemy = EnemySpirit()
        self.enemy_group = pygame.sprite.Group()

        self.hero = Hero()
        self.hero_group = pygame.sprite.Group(self.hero)

    # 开始游戏
    def start_game(self):
        # 设置帧率
        while True:
            self.clock.tick(FPS)
            # 事件监听
            self.__event_listen()
            # 碰撞检测
            self.__spirits_collide()
            # 绘制图像
            self.__image_drew()
            # 更新显示
            pygame.display.update()

    def __event_listen(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print("游戏退出")
                self.__game_over()
            elif event.type == ENEMY_EVENT:
                enemy = EnemySpirit()
                self.enemy_group.add(enemy)
            elif event.type == FIRE_BULLET_EVENT:
                self.hero.fire()
            elif event.type == WAKE_FLAME_EVENT:
                self.hero.wake_flame()

    def __spirits_collide(self):
        pygame.sprite.groupcollide(self.enemy_group, self.hero.bullet_group, True, True)
        if not hero_invincible:
            aa = pygame.sprite.groupcollide(self.enemy_group, self.hero_group, True, True)
            if len(aa) > 0:
                print("英雄牺牲....")
                print("游戏结束")
                self.__game_over()
        else:
            aa = pygame.sprite.groupcollide(self.enemy_group, self.hero_group, True, False)

    def __image_drew(self):
        self.bj_group.update()
        self.bj_group.draw(self.screen)

        self.enemy_group.update()
        self.enemy_group.draw(self.screen)

        self.hero_group.update()
        self.hero_group.draw(self.screen)

        self.hero.bullet_group.update()
        self.hero.bullet_group.draw(self.screen)

    @staticmethod
    def __game_over():
        pygame.quit()
        exit()


if __name__ == '__main__':
    game = PlaneGame()
    game.start_game()
